package com.outsourcing.bottle.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ext.SatelliteMenu;
import android.view.ext.SatelliteMenu.SateliteClickedListener;
import android.view.ext.SatelliteMenuItem;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.db.PushNoticeInfoTable;
import com.outsourcing.bottle.domain.LoginUserInfoEntry;
import com.outsourcing.bottle.domain.NoticeEntry;
import com.outsourcing.bottle.domain.NoticeInfo;
import com.outsourcing.bottle.domain.PushNoticeInfo;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ImageLoader;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.widget.CustomListView;
/**
 * 
 * @author 06peng
 *
 */
public class NoticeListActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener {

	private ImageView backView;
	private ImageView moreView;
//	private ImageView noticeView;
//	private LinearLayout messageCountLayout;
//	private TextView countView;
	
	private CustomListView listView;
	
	private int visibleLastIndex = 0; // 最后的可视项索引
	public int visibleItemCount; // 当前窗口可见项总数
	private View loadMoreView;
	
	private LinearLayout bottomLayout;
	private ImageView avatarView;
	private TextView contentView;
	private TextView btnCount;
//	private ImageView messageView;
	private int newNoticeCount;
	private int newMessageCount;
	private int newBottleFeedCount;
	private int newExchangeFeedCount;
	private int newMaybeKownCount;
	private String message_content;
	private String message_avatar;
	
	private final int init_notice_info = 1;
	private final int error = 2;
	private final int user_baseinfo_notfull = 3;
	private final int complete_info = 4;
	private final int accept_friend = 5;
	private final int reject_friend = 6;
	private final int more = 7;
	private int page = 1;
	
	private final int menu_uploadphoto = 105;
	private final int menu_exprofile = 14;
	private final int menu_exphoto = 13;
	private final int menu_gainbt = 12;
	private final int menu_sendbt = 11;
	
	private Handler handler;
	private List<NoticeEntry> noticeList;
	private ImageLoader userImageLoader;
	private ImageLoader photoImageLoader;
	private NoticeAdapter adapter;
	private PushBroadcastReceiver receiver;
	private PushNoticeInfo pushInfo;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.notice_list);
		handler = new Handler(this);
		userImageLoader = new ImageLoader(this, AppContext.UserAvatarIcon);
		photoImageLoader = new ImageLoader(this, AppContext.BottleTimelineIcon);
		initWidget();
		initSateMenu();
		UICore.eventTask(this, this, init_notice_info, "init_notice_info", null);
	}
	
	private void initWidget() {
		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		moreView = (ImageView) findViewById(R.id.topbar_menu);
		moreView.setOnClickListener(this);
//		noticeView = (ImageView) findViewById(R.id.topbar_notice);
//		noticeView.setOnClickListener(this);
//		messageCountLayout = (LinearLayout) findViewById(R.id.notice_layout);
//		messageCountLayout.setVisibility(View.GONE);
//		countView = (TextView) findViewById(R.id.notice_count);
		listView = (CustomListView) findViewById(R.id.notice_list);
		loadMoreView = LayoutInflater.from(this).inflate(R.layout.refreshable_list_footer, null);
		loadMoreView.setVisibility(View.GONE);
		listView.addFooterView(loadMoreView);
		listView.setonRefreshListener(new CustomListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				page = 1;
				new Thread() {
					public void run() {
						initNoticeInfo();
					};
				}.start();
			}
		});
		listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				int itemsLastIndex = adapter.getCount() + 1; // 数据集最后一项的索引
				int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项 和 head项
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {
					// 如果是自动加载,可以在这里放置异步加载数据的代码
					loadMoreView.setVisibility(View.VISIBLE);
					page++;
					new Thread() {
						@Override
						public void run() {
							loadMoreNoticeInfo();
						}
					}.start();
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				listView.setFirstVisiableItem(firstVisibleItem);
				NoticeListActivity.this.visibleItemCount = visibleItemCount;
				visibleLastIndex = firstVisibleItem + visibleItemCount;
			}
		});
		bottomLayout = (LinearLayout) findViewById(R.id.notice_bottom_layout);
		bottomLayout.setOnClickListener(this);
		avatarView = (ImageView) findViewById(R.id.notice_avatar);
		contentView = (TextView) findViewById(R.id.notice_text);
		btnCount = (TextView) findViewById(R.id.notice_number);
//		messageView = (ImageView) findViewById(R.id.notice_message_count);
//		messageView.setOnClickListener(this);
//		messageView.setVisibility(View.VISIBLE);
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (arg2 == adapter.getCount() + 1) {
					return;
				}
				NoticeEntry entry = noticeList.get(arg2 - 1);
				/**
				 * 通知类型，选择项：照片类通知（0）、瓶子类通知（1）、接受好友申请通知（2）、申请好友通知（3）
				 * */
				if (entry.getNotice_type() == 0) {
					Intent intent = new Intent(NoticeListActivity.this, UserPhotoActivity.class);
					intent.putExtra("ouid", entry.getUid());
					intent.putExtra("picid", entry.getNotice_picid());
					startActivity(intent);
				} else if (entry.getNotice_type() == 1) {
					Intent intent = new Intent(NoticeListActivity.this, BottleDetailActivity.class);
					intent.putExtra("btid", entry.getNotice_btid());
					intent.putExtra("type", 1);
					startActivity(intent);
				} else if (entry.getNotice_type() == 2) {
					Intent intent = new Intent(NoticeListActivity.this, UserSpaceActivity.class);
					intent.putExtra("ouid", entry.getUid());
					startActivity(intent);
				} else if (entry.getNotice_type() == 3) {
					doFriendAction(entry.getNickname(), entry.getUid());
				}
			}
		});
	}
	
	private void updateUI() {
		pushNoticeUpdateUI();
		if (noticeList != null && !noticeList.isEmpty()) {
			adapter = new NoticeAdapter();
			listView.setAdapter(adapter);
		}
	}
	
	@Override
	public void onClick(View v) {
		if (v == backView) {
			finish();
		} else if (v == moreView) {
			Intent intent = new Intent(NoticeListActivity.this, HomeActivity.class);
			intent.putExtra("currentItem", 1);
			startActivity(intent);
			finish();
		
		} 
//		else if (v == noticeView) {
//			Intent intent = new Intent(this, MessageListActivity.class);
//			startActivity(intent);
//		}
		else if (v == bottomLayout) {
			doFeedsAction();
		} 
//		else if (v == messageView) {
//			doMessageAction();
//		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_notice_info:
			updateUI();
			listView.onRefreshComplete();
			receiver = new PushBroadcastReceiver();
			IntentFilter filter = new IntentFilter();
			filter.addAction("push");
			registerReceiver(receiver, filter);
			break;
		case user_baseinfo_notfull:
			showChoseMes(getString(R.string.exchange_complete_profile_tips), complete_info);
			break;
		case accept_friend:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, init_notice_info, "init_notice_info", null);
			break;
		case reject_friend:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, init_notice_info, "init_notice_info", null);
			break;
		case error:
			onToast((String) msg.obj);
			break;
		case more:
			adapter.notifyDataSetChanged();
			loadMoreView.setVisibility(View.GONE);
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case init_notice_info:
			initNoticeInfo();
			break;
		case accept_friend:
			acceptFriend((String) obj);
			break;
		case reject_friend:
			rejectFriend((String) obj);
			break;
		default:
			break;
		}
	}

	private void initNoticeInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_mynoticeslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&count=" + 20);
		url.append("&page=" + page);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			NoticeInfo info = gson.fromJson(result, NoticeInfo.class);
			if (info.getResults().getAuthok() == 0) {
				Message msg = Message.obtain(handler, error, info.getResults().getErrmsg());
				handler.sendMessage(msg);
			} else {
				getPushNotice();
				noticeList = info.getNotices_list();
				PushNoticeInfoTable table = new PushNoticeInfoTable();
				pushInfo = table.getPushNoticeInfo(AppContext.getInstance().getLogin_uid());
				if (null != pushInfo) {
					newBottleFeedCount = pushInfo.getNew_btfeed_count();
					newExchangeFeedCount = pushInfo.getNew_exfeed_count();
					newMessageCount = pushInfo.getNew_message_count();
					newNoticeCount = pushInfo.getNew_notice_count();
					newMaybeKownCount = pushInfo.getNew_maybeknow_count();
					message_content = pushInfo.getMessage_content();
					message_avatar = pushInfo.getMessage_avatar();
				}
		
				handler.sendEmptyMessage(init_notice_info);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void getPushNotice() {
		StringBuffer url = new StringBuffer(UrlConfig.push_notice);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultObj = obj.getJSONObject("results");
				if (resultObj.getInt("authok") == 1) {
					JSONObject pushObj = obj.getJSONObject("push_notice");
					PushNoticeInfoTable table = new PushNoticeInfoTable();
					PushNoticeInfo pushInfo = new PushNoticeInfo();
					table.clearTable();
					pushInfo.setMessage_avatar(pushObj.getString("message_avatar"));
					pushInfo.setMessage_content(pushObj.getString("message_content"));
					pushInfo.setNew_btfeed_count(pushObj.getInt("new_btfeed_count"));
					pushInfo.setNew_exfeed_count(pushObj.getInt("new_exfeed_count"));
					pushInfo.setNew_message_count(pushObj.getInt("new_message_count"));
					pushInfo.setNew_notice_count(pushObj.getInt("new_notice_count"));
					pushInfo.setNew_maybeknow_count(pushObj.getInt("new_maybeknow_count"));
					table.savePushNoticeInfo(pushInfo, AppContext.getInstance().getLogin_uid());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void loadMoreNoticeInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_mynoticeslist);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&count=" + 20);
		url.append("&page=" + page);
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			NoticeInfo info = gson.fromJson(result, NoticeInfo.class);
			if (info.getResults().getAuthok() == 0) {
				Message msg = Message.obtain(handler, error, info.getResults().getErrmsg());
				handler.sendMessage(msg);
			} else {
				List<NoticeEntry> moreList = info.getNotices_list();
				noticeList.addAll(moreList);
				handler.sendEmptyMessage(more);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void acceptFriend(String ouid) {
		String url = UrlConfig.accept_friend;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("ouid", ouid);
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
	        if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int success = resultObj.getInt("success");
	        	if (success == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, accept_friend, successmsg);
					handler.sendMessage(msg);
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void rejectFriend(String ouid) {
		String url = UrlConfig.reject_friend;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("ouid", ouid);
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
	        if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int success = resultObj.getInt("success");
	        	if (success == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, accept_friend, successmsg);
					handler.sendMessage(msg);
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class NoticeAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return noticeList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return noticeList.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView != null && convertView.getId() == R.id.notice_list_item_layout) {
				holder = (ViewHolder) convertView.getTag();
			} else {
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.notice_list_item, null);
				holder = new ViewHolder();
				holder.avatarView = (RemoteImageView) convertView.findViewById(R.id.notice_item_avatar);
				holder.nameView = (TextView) convertView.findViewById(R.id.notice_item_nameandcontent);
				holder.timeView = (TextView) convertView.findViewById(R.id.notice_item_time);
				holder.photoView = (ImageView) convertView.findViewById(R.id.notice_item_photo);
				holder.layout = (RelativeLayout) convertView.findViewById(R.id.notice_item_photo_layout);
				convertView.setTag(holder);
			}
			final NoticeEntry entry = noticeList.get(position);
			if (entry != null) {
				if (entry.getIsnew() == 1) {
					Drawable drawable = getResources().getDrawable(R.drawable.star);
					holder.nameView.setCompoundDrawables(null, null, drawable, null);
				} 
				holder.avatarView.setDefaultImage(R.drawable.avatar_default_big);
				holder.avatarView.setImageUrl(entry.getAvatar(), position, listView);
				String name = "<font color=#419AD9>" + entry.getNickname() + "</font>";
				holder.nameView.setText(Html.fromHtml(name + "&nbsp;" + (entry.getIsnew() == 1 ? "<font color=red>"+entry.getContent()+"</font>" : entry.getContent())));
				holder.timeView.setText(entry.getNotice_time());
				if (TextUtil.notEmpty(entry.getNotice_smallpic())) {
					holder.layout.setVisibility(View.VISIBLE);
					photoImageLoader.DisplayImage(entry.getNotice_smallpic(), holder.photoView, R.drawable.album_nophoto);
					holder.photoView.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							Intent intent = new Intent(NoticeListActivity.this, UserPhotoActivity.class);
							intent.putExtra("picid", entry.getNotice_picid());
							intent.putExtra("ouid", entry.getUid());
							startActivity(intent);
						}
					});
				} else {
					holder.layout.setVisibility(View.GONE);
				}
				holder.avatarView.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Intent spaceIntent = new Intent(NoticeListActivity.this, UserSpaceActivity.class);
						spaceIntent.putExtra("ouid", entry.getUid());
						startActivity(spaceIntent);
					}
				});
			}
			return convertView;
		}
		
	}
	
	public static class ViewHolder {
		RemoteImageView avatarView;
		TextView nameView;
		TextView timeView;
		ImageView photoView;
		RelativeLayout layout;
	}
	
	private void initSateMenu() {
		SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu);
		menu.setVisibility(View.VISIBLE);
		if (CanvasWidth >= 480) {
			menu.setSatelliteDistance(200);
		} else {
			menu.setSatelliteDistance(100);
		}
		List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>();
		items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile));
		items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto));
		items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt));
		items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt));
		items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto));
		menu.addItems(items);
		menu.setOnItemClickedListener(new SateliteClickedListener() {

			public void eventOccured(int id) {
				switch (id) {
				case menu_sendbt: //扔瓶子
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent throwIntent = new Intent(NoticeListActivity.this, ChooseBottleActivity.class);
								throwIntent.putExtra("type", "throw");
								startActivity(throwIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_gainbt: //捞瓶子
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent tryIntent = new Intent(NoticeListActivity.this, ChooseBottleActivity.class);
								tryIntent.putExtra("type", "try");
								startActivity(tryIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_exphoto:  //交换照片
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent exchangeInfoIntent = new Intent(NoticeListActivity.this, ChooseFriendActivity.class);
								exchangeInfoIntent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE);
								startActivity(exchangeInfoIntent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_exprofile: //交换资料
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								LoginUserInfoTable userTable = new LoginUserInfoTable();
								LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid());
								if (userEntry.getBasicinfo_fullfill() == 0) {
									handler.sendEmptyMessage(user_baseinfo_notfull);
								} else {
									Intent exchangeFileIntent = new Intent(NoticeListActivity.this, ChooseFriendActivity.class);
									exchangeFileIntent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE);
									startActivity(exchangeFileIntent);
								}
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				case menu_uploadphoto:
					new Thread() {
						public void run() {
							try {
								Thread.sleep(500);
								Intent intent = new Intent(NoticeListActivity.this, ExpandEditActivity.class);
								Bundle extras = new Bundle();
								extras.putString("from_type", AppContext.UPLOAD_PHOTO);
								extras.putInt("albumid", 0);
								extras.putInt("ouid", AppContext.getInstance().getLogin_uid());
								intent.putExtras(extras);
								startActivity(intent);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						};
					}.start();
					break;
				default:
					break;
				}
			}
		});
	}
	
	@Override
	public void sysMesPositiveButtonEvent(int what) {
		if (what == complete_info) {
			Intent intent = new Intent(this, SettingActivity.class);
			startActivity(intent);
		} 
	}
	
	private void doFriendAction(String nickname, final int ouid) {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		String[] choices;
		choices = new String[3];
		choices[0] = nickname + getString(R.string.user_info_space); 
		choices[1] = getString(R.string.bottle_txt_notice_accept); 
		choices[2] = getString(R.string.bottle_txt_notice_reject);
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							Intent intent = new Intent(NoticeListActivity.this, UserSpaceActivity.class);
							intent.putExtra("ouid", ouid);
							startActivity(intent);
							break;
						case 1:
							UICore.eventTask(NoticeListActivity.this,
									NoticeListActivity.this, accept_friend, "accept_friend", String.valueOf(ouid));
							break;
						case 2:
							UICore.eventTask(NoticeListActivity.this,
									NoticeListActivity.this, reject_friend, "reject_friend", String.valueOf(ouid));
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}
	
	public void doMessageAction() {
		
		final Context dialogContext = new ContextThemeWrapper(this,
				android.R.style.Theme_Light);
		String[] choices = new String[2];
		if (newNoticeCount > 0) {
			choices[0] = newNoticeCount + getString(R.string.bottle_txt_notice_list);
		} else {
			choices[0] = getString(R.string.bottle_txt_notice_list);
		}
		if (newMessageCount > 0) {
			choices[1] = newMessageCount + getString(R.string.bottle_txt_message_list);
		} else {
			choices[1] = getString(R.string.bottle_txt_message_list);
		}
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (which == 0) {
							Intent intent = new Intent(NoticeListActivity.this, NoticeListActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(NoticeListActivity.this, MessageListActivity.class);
							startActivity(intent);
						}
					}
				});
		builder.create().show();
	}
	
	public void doFeedsAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		final List<String> choices = new ArrayList<String>(); 
		if (newBottleFeedCount > 0) {
			choices.add(newBottleFeedCount + getString(R.string.bottle_txt_new_bottle_feed));
		}
		if (newExchangeFeedCount > 0) {
			choices.add(newExchangeFeedCount + getString(R.string.bottle_txt_new_exchange_feed));
		}
		if (newNoticeCount > 0) {
			choices.add(newNoticeCount + getString(R.string.bottle_txt_notice_list));
		}
		if (newMessageCount > 0) {
			choices.add(newMessageCount + getString(R.string.bottle_txt_message_list));
		}
		if (newMaybeKownCount > 0) {
			choices.add(newMaybeKownCount + getString(R.string.bottle_txt_new_maybe_kown));
		}
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices);
		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_bottle_feed)) != -1) {
							Intent intent = new Intent(NoticeListActivity.this, HomeActivity.class);
							AppContext.getInstance().setCurrentItem(1);
							startActivity(intent);
						} else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_exchange_feed)) != -1) {
							Intent intent = new Intent(NoticeListActivity.this, HomeActivity.class);
							AppContext.getInstance().setCurrentItem(0);
							startActivity(intent);
						} else if (choices.get(which).indexOf(getString(R.string.bottle_txt_notice_list)) != -1) {
							Intent intent = new Intent(NoticeListActivity.this, NoticeListActivity.class);
							startActivity(intent);
						} else if (choices.get(which).indexOf(getString(R.string.bottle_txt_message_list)) != -1) {
							Intent intent = new Intent(NoticeListActivity.this, MessageListActivity.class);
							startActivity(intent);
						} else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_maybe_kown)) != -1) {
							Intent intent = new Intent(NoticeListActivity.this, HomeActivity.class);
							AppContext.getInstance().setCurrentItem(2);
							AppContext.getInstance().setGotoMaybeKown(true);
							startActivity(intent);
						}
					}
				});
		builder.create().show();
	}
	
	public void pushNoticeUpdateUI() {
		if (newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount > 0) {
			bottomLayout.setVisibility(View.VISIBLE);
			contentView.setText(message_content);
			btnCount.setText(newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount  + "");
			userImageLoader.DisplayImage(message_avatar, avatarView, R.drawable.avatar_default_big);
		} else {
			bottomLayout.setVisibility(View.GONE);
		}
	}
	
	public class PushBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				newBottleFeedCount = bundle.getInt("bottle_feed_count");
				newExchangeFeedCount = bundle.getInt("exchange_feed_count");
				newMessageCount = bundle.getInt("message_count");
				newNoticeCount = bundle.getInt("notice_count");
				message_content = bundle.getString("message_content");
				message_avatar = bundle.getString("message_avatar");
				newMaybeKownCount = bundle.getInt("maybe_kown_count");
				pushNoticeUpdateUI();
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (receiver != null) {
				unregisterReceiver(receiver);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
